package com.weaver.qfengx.api.ding;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMediaUploadRequest;
import com.dingtalk.api.response.OapiMediaUploadResponse;
import com.google.common.collect.Maps;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;
import com.weaver.qfengx.RequestUtils;
import com.weaver.qfengx.StringUtils;
import com.weaver.qfengx.api.ding.config.DingConfig;
import com.weaver.qfengx.entity.Result;
import okhttp3.OkHttpClient;
import okhttp3.Response;

import java.io.IOException;
import java.util.Map;

/**
 * 钉钉相关集成APi
 */
public class DingApiService {

    private String host = "";
    private OkHttpClient client;

    public DingApiService(OkHttpClient client, String host) {
        this.client = client;
        this.host = host;
    }

    public DingApiService(String host) {
        this.client = new OkHttpClient();
        this.host = host;
    }

    private Result createResult(Response response) throws IOException {
        if (response.isSuccessful()) {
            String respBody = response.body().string();
            System.out.println(respBody);
            JSONObject jsonObject = JSONObject.parseObject(respBody);
            if (StringUtils.equals("0", jsonObject.getString("errcode"))) {
                return Result.ok();
            } else {
                return Result.fail(jsonObject.getString("errmsg")).setData(respBody);
            }
        } else {
            return Result.fail("请求异常");
        }
    }


    public Result getToken(String appkey, String appsecret) throws IOException {
        Map<String, String> reqParam = Maps.newHashMap();
        reqParam.put("appkey", appkey);
        reqParam.put("appsecret", appsecret);
        Response response = RequestUtils.doGetWithoutChange(this.client, this.host + DingConfig.getToken, reqParam);
        if (response.isSuccessful()) {
            String respBody = response.body().string();
            System.out.println(respBody);
            JSONObject jsonObject = JSONObject.parseObject(respBody);
            if (StringUtils.equals("0", jsonObject.getString("errcode"))) {
                return Result.ok(jsonObject.getString("access_token"));
            } else {
                return Result.fail(jsonObject.getString("errmsg")).setData(respBody);
            }
        } else {
            return Result.fail("请求异常");
        }
    }

    // 发送工作通知
    public Result messageCorpconversationAsyncsend_v2(String token,
                                                      String agent_id, String userid_list,
                                                      String dept_id_list, Boolean to_all_user, Map<String, Object> msg) throws IOException {
        // body体内容
        Map<String, Object> reqParam = Maps.newHashMap();
        reqParam.put("agent_id", agent_id);
        if (StringUtils.isNotEmpty(userid_list)) {
            reqParam.put("userid_list", userid_list);
        }
        if (StringUtils.isNotEmpty(dept_id_list)) {
            reqParam.put("dept_id_list", dept_id_list);
        }
        reqParam.put("to_all_user", to_all_user);
        reqParam.put("msg", msg);
        Response response = RequestUtils.doPostByJson(this.client, this.host + DingConfig.messageCorpconversationAsyncsend_v2 + "?access_token=" + token, reqParam);
        return createResult(response);
    }

    // 发送工作通知
    public Result smartbotMsgPush(String token,
                                  String agent_id, String userid_list,
                                  String dept_id_list, Boolean to_all_user, Map<String, Object> msg) throws IOException {
        // body体内容
        Map<String, Object> reqParam = Maps.newHashMap();
        reqParam.put("agent_id", agent_id);
        if (StringUtils.isNotEmpty(userid_list)) {
            reqParam.put("userid_list", userid_list);
        }
        if (StringUtils.isNotEmpty(dept_id_list)) {
            reqParam.put("dept_id_list", dept_id_list);
        }
        reqParam.put("to_all_user", to_all_user);
        reqParam.put("msg", msg);
        Response response = RequestUtils.doPostByJson(this.client, this.host + DingConfig.smartbotMsgPush + "?access_token=" + token, reqParam);
        return createResult(response);
    }

    public Result workrecord(String token, String userid, int offset, int limit, int status) throws IOException {
        // body体内容
        Map<String, Object> reqParam = Maps.newHashMap();
        reqParam.put("userid", userid);
        reqParam.put("offset", offset);
        reqParam.put("limit", limit);
        reqParam.put("status", status);
        Response response = RequestUtils.doPostByJson(this.client, this.host + DingConfig.workrecordGetByUserid + "?access_token=" + token, reqParam);
        return createResult(response);
    }

    // 获取服务号列表
    public Result serviceaccountList(String token, int pageStart, int pageSize) throws IOException {
        // body体内容
        Map<String, Object> reqParam = Maps.newHashMap();
        reqParam.put("pageStart", pageStart);
        reqParam.put("pageSize", pageSize);
        Response response = RequestUtils.doPostByJson(this.client, this.host + DingConfig.serviceaccountList + "?access_token=" + token, reqParam);
        if (response.isSuccessful()) {
            String respBody = response.body().string();
            System.out.println(respBody);
            JSONObject jsonObject = JSONObject.parseObject(respBody);
            if (StringUtils.equals("0", jsonObject.getString("errcode"))) {
                return Result.ok(jsonObject.getString("items"));
            } else {
                return Result.fail(jsonObject.getString("errmsg")).setData(respBody);
            }
        } else {
            return Result.fail("请求异常");
        }
    }

    // 消息群发
    public Result massSend(String token, String unionid, String media_id,
                           boolean is_to_all, String msg_type, String text_content,
                           String uuid, String userid_list, String dep_id_list,
                           Boolean is_preview, Map<String, Object> msg_body) throws IOException {
        Map<String, Object> reqParam = Maps.newHashMap();
        reqParam.put("unionid", unionid);
        if (StringUtils.isNotEmpty(media_id)) {
            reqParam.put("media_id", media_id);
        }
        reqParam.put("is_to_all", is_to_all);
        reqParam.put("msg_type", msg_type);
        if (StringUtils.isNotEmpty(text_content)) {
            reqParam.put("text_content", text_content);
        }
        reqParam.put("uuid", uuid);
        if (StringUtils.isNotEmpty(userid_list)) {
            reqParam.put("userid_list", userid_list);
        }
        if (StringUtils.isNotEmpty(dep_id_list)) {
            reqParam.put("dep_id_list", dep_id_list);
        }
        if (is_preview != null) {
            reqParam.put("is_preview", is_preview);
        }
        if (msg_body != null && !msg_body.isEmpty()) {
            reqParam.put("msg_body", msg_body);
        }
        Response response = RequestUtils.doPostByJson(this.client, this.host + DingConfig.massSend + "?access_token=" + token, reqParam);
        return createResult(response);
    }

    // 消息卡片列表
    public Result newsList(String token, String unionid, int page_start, int page_size) throws IOException {
        Map<String, Object> reqParam = Maps.newHashMap();
        reqParam.put("unionid", unionid);
        reqParam.put("page_start", page_size);
        Response response = RequestUtils.doPostByJson(this.client, this.host + DingConfig.newsList + "?access_token=" + token, reqParam);
        return createResult(response);
    }

    // 上传资源文件
    public Result mediaUpload(String token, String type, String filepath) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(this.host + DingConfig.mediaUpload);
        OapiMediaUploadRequest req = new OapiMediaUploadRequest();
        req.setType(type);
        // 要上传的媒体文件
        FileItem item = new FileItem(filepath);
        req.setMedia(item);
        OapiMediaUploadResponse rsp = client.execute(req, token);
        System.out.println(rsp.getBody());
        return Result.ok(rsp.getBody());
    }

    public static void main(String[] args) {
        // 发送钉钉消息
        try {
            DingApiService apiService = new DingApiService("https://oapi.dingtalk.com");
//            Result result = apiService.getToken("dingsqro09fdhd7icqaj", "LAImoB9JP-i5ReqXiTly_IGna8Gj0aGx87d4C7eSwEl-KYIlpU9dlJwzFPR_oMrO");
            Result result = apiService.getToken("dingnfh9n31c2bsr7rbz", "xf4iVH2L3aEqYcPxddaBlJpz6WSFglrL-JPly0AWdKJjSE-B1qLn5rTkbzBO3yA6");
            System.out.println(result);
            String token = StringUtils.val(result.getData());
            if (result.isOk()) {
//                Map<String, Object> msg = Maps.newHashMap();
//                msg.put("msgtype", "text");
//                Map<String, Object> text = Maps.newHashMap();
//                text.put("content", "消息测试" + DateUtils.datetime());
//                msg.put("text", text);
//                System.out.println(msg.toString());
////                Result msgResult = apiService.messageCorpconversationAsyncsend_v2(StringUtils.val(result.getData()), "1179323730", "", "", true, msg);
////                Result msgResult = apiService.smartbotMsgPush(StringUtils.val(result.getData()), "1179323730", "", "", true, msg);
////                Result workrecord = apiService.workrecord(StringUtils.val(result.getData()), "13918071879", 0, 10, 0);
//                Result res1 = apiService.serviceaccountList(StringUtils.val(result.getData()), 1, 10);
//                System.out.println(res1);
////                Result msgResult = apiService.smartbotMsgPush(StringUtils.val(result.getData()), "1174529451", "13918071879", "", false, msg);
////                String unionid = "SnG9mwVhYyXwYBnXii3aYJQiEiE";
//                String unionid = "rAU0aKLODtswymO3h78D3QiEiE";
//                // 普通文字
////                Result res = apiService.massSend(StringUtils.val(result.getData()), unionid, "", false,
////                        "text", "send test", IDUtils.uuid(), "13918071879",
////                        "", false, null);
//                // 卡片消息
//                // action_card
//                Map<String, Object> msg_body = Maps.newHashMap();
//                Map<String, Object> info = Maps.newHashMap();
////                info.put("single_title", "点击查看");
//                info.put("btn_orientation", "1");
//                Map<String, String> button_list = Maps.newHashMap();
//                button_list.put("action_url", "https://www.e-cology.com.cn/spa/portal/static4mobilelogin/index.html#/login");
//                button_list.put("title", "点击查看");
//                info.put("button_list", Lists.newArrayList(button_list));
//                info.put("title", "您有一条流程已完成自动审批");
////                info.put("single_url", "https://www.e-cology.com.cn/spa/portal/static4mobilelogin/index.html#/login");
//                info.put("markdown", "![协同办公](http://files.qfengx.cn/oa.png)\n" +
//                        "\n" +
//                        "##### 关于启动流程梳理发文的通知\n" +
//                        "##### 你已自动完成审批\n");
////                        + "---\n" +
////                        "[点击查看](https://www.e-cology.com.cn/spa/portal/static4mobilelogin/index.html#/login)");
//                msg_body.put("action_card", info);
//                Map<String, String> file = Maps.newHashMap();
//                file.put("media_id", "@lALPDfmVSmn-ig3NAQfNAdg");
//                msg_body.put("file", file);

//                Result res = apiService.massSend(StringUtils.val(result.getData()), unionid,
//                        "@lALPDfmVSmn-ig3NAQfNAdg", false,
//                        "action_card", "hello", IDUtils.uuid(),
//                        "13918071879",
//                        "", false, msg_body);
//                Result res = apiService.newsList(StringUtils.val(result.getData()), unionid, 0, 10); // @lALPDfmVSmn-ig3NAQfNAdg
                Result res = apiService.mediaUpload(StringUtils.val(result.getData()), "image", "C:\\Users\\Qfeng\\Desktop\\微信图片_20210511140422.png");
//                Result res = apiService.serviceaccountList(token, 1, 10);
                System.out.println(res);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
